﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Clipper.Model;
using System.Collections.ObjectModel;
using System.Threading;
using Global;
using System.Windows;
using System.Windows.Controls;
using Communication;
using System.ComponentModel;
using Clipper.BLL.Supplier;
using Clipper.Model.EnumModel;
using Clipper.Model.DetectionModel;
using Clipper.Model.ViewModel;
using Clipper.Model.DataBaseModel;

namespace Clipper.BLL.DetectChain
{
    /// <summary>
    /// 检测流程操作类
    /// </summary>
    public class DetectChainHelper
    {
        #region 变量
        static DAL.ReactionStripPosition mPositionDal = new DAL.ReactionStripPosition();
        static System.Timers.Timer detectTimer, cupLoddTimer;

        static BLL.DataBaseBLL.StandardCurveData standardBll = new DataBaseBLL.StandardCurveData();
        /// <summary>
        /// 检测链运行timer
        /// </summary>
        public static System.Timers.Timer DetectTimer
        {
            get
            {
                return detectTimer;
            }
            set
            {
                detectTimer = value;
            }
        }
        //接收数据
        //static System.Timers.Timer mRecieveTimer;

        /// <summary>
        /// 定时查询温度
        /// </summary>
        static System.Timers.Timer mTemperatureTimer;

        /// <summary>
        /// 定时检查门的状态
        /// </summary>
        static System.Timers.Timer mDoorTimer;

        /// <summary>
        /// 孵育位温度状态显示
        /// </summary>
        static System.Timers.Timer IncuBoxStateTime;

        static bool through = true;//尽心报警闪烁一次 默认为 TRUE

        /// <summary>
        /// 冷却处温度设置
        /// </summary>
        static System.Timers.Timer ReagentColdStateTime;

        static bool reagentColdThrough = true;


        /// <summary>
        /// 结束倒计时timer
        /// </summary>
        static System.Timers.Timer mTimerCountDown = new System.Timers.Timer();
        public static DateTime mdtStart;//开始时间

        /// <summary>
        /// 一步法检测链实例
        /// </summary>
        static ApplianceComponent mDetectChain = null;
        /// <summary>
        /// 两步法检测链实例
        /// </summary>
        static DeliveryWarehouse mDetectChainTwoStep = null;
        static int detectTemp = 0;

        #endregion

        #region 属性
        static DetectionOrder mDetectionOrder = null;
        /// <summary>
        /// 反应条排序
        /// </summary>
        public static DetectionOrder DetectionOrder
        {
            get
            {
                if (mDetectionOrder == null)
                {
                    mDetectionOrder = new DetectionOrder();
                }
                return mDetectionOrder;
            }
        }
        #endregion 

        #region 运行控制
        /// <summary>
        /// 生成检测流程
        /// </summary>
        /// <returns></returns>
        public static void InitDetectChain()
        {
            //一步法

            AddReagent1AndSample addReagent1AndSample = new AddReagent1AndSample();
            IncubationBox incubationBox = new IncubationBox();
            AddReagent2 addReagent2 = new AddReagent2();
            IncubationBox incubationBox1 = new IncubationBox();
            AddReagent2 addReagent3 = new AddReagent2();
            DetectionHouse detectionHouse = new DetectionHouse();


            addReagent1AndSample.NextComponent = incubationBox;
            incubationBox.NextComponent = addReagent2;
            addReagent2.NextComponent = incubationBox1;
            incubationBox1.NextComponent = addReagent3;
            addReagent3.NextComponent = detectionHouse;

            mDetectChain = addReagent1AndSample;

            //初始化事件
            Can.SendCmdEvent += new Can.SendDelegate(Can_Decode_Send);
            Can.Decode_Receive += new Can.DecodeDelegate(Can_Decode_Receive);
            mTimerCountDown.Elapsed += new System.Timers.ElapsedEventHandler(mTimerAllCD_Elapsed);
            mTimerCountDown.Interval = 1000;
            IncubationBox.mTimerCountDown.Elapsed += new System.Timers.ElapsedEventHandler(mTimerCountDown_Elapsed);
            IncubationBox.mTimerCountDown.Interval = 1000;
            ControlBase.mSendBuffer.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(mSendBuffer_CollectionChanged);


            //定义一个杯条的集合
            //  ObservableCollection<CupStrip> cupStrip= ServiceProvider.CupStrip;
            ServiceProvider.CupStrip = new ObservableCollection<CupStrip>();

            for (int i = 0; i < 4; i++)
            {
                CupStrip strip = new CupStrip();
                //if (i == 0) //置孔位加载状态
                //{
                //strip.setStatus(CupStrip.ReactionStripStatusEnum.LOAD);
                //}
                strip.setStatus(CupStrip.ReactionStripStatusEnum.UNLOAD);
                strip.StripSeat = i;

                for (int j = 0; j < 4; j++)
                {
                    Cup cup = new Cup();
                    //if (i == 0) //置孔位状态
                    //{
                    //cup.setStatus(Cup.CupHoleStatusEnum.FULL);
                    //}
                    cup.setStatus(Cup.CupHoleStatusEnum.EMPTY);
                    cup.HoleSeat = j;
                    cup.inStripSeat = i;
                    strip.Cups.Add(cup);
                }
                ServiceProvider.CupStrip.Add(strip);
            }
            //创建一个对象
            ServiceProvider.Monitor.DisplayCup = new ObservableCollection<DisplayCup>();
            for (int i = 0; i < 16; i++)
            {
                DisplayCup displayObj = new DisplayCup();
                displayObj.CupSeatID = i + 1;
                displayObj.SampleInfoID = 0;
                displayObj.CupStatus = "空";
                displayObj.DetectItem = "";
                ServiceProvider.Monitor.DisplayCup.Add(displayObj);
            }

            //CupDetectResultInformation reaction = new CupDetectResultInformation();
            //reaction.DetectItem = "PT";
            //reaction.SampleInfoID = 66;
            //reaction.DetectResult = "12.1";

            //ServiceProvider.Monitor.DetectResultListToady.Add(reaction);
        }

        #region 事件
        //添加超时命令事件
        static void mSendBuffer_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                //ReSend();

            }
        }
        //孵育倒计时事件
        static void mTimerCountDown_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (ServiceProvider.Monitor.IncubationBoxReactionStrips.Count > 1)
                {
                    IncubationBox.mdtStart = ServiceProvider.Monitor.IncubationBoxReactionStrips.First(tt => tt.IncubatorEnd > DateTime.Now).IncubatorEnd;
                }
                else if (ServiceProvider.Monitor.IncubationBoxReactionStrips.Count == 1)
                {
                    IncubationBox.mdtStart = ServiceProvider.Monitor.IncubationBoxReactionStrips[0].IncubatorEnd;
                }
            }
            catch
            {

                ServiceProvider.Monitor.IncubationNextCD = "00:00";
                IncubationBox.mTimerCountDown.Stop();
                IncubationBox.mIsCDRunning = false;
            }
            TimeSpan ts = IncubationBox.mdtStart - DateTime.Now;

            if (ts < TimeSpan.Zero)
            {
                ServiceProvider.Monitor.IncubationNextCD = "00:00";
                IncubationBox.mTimerCountDown.Stop();
                IncubationBox.mIsCDRunning = false;
            }
            else
            {
                ServiceProvider.Monitor.IncubationNextCD = string.Format("{0:D2}:{1:D2}", ts.Minutes, ts.Seconds);
            }
        }
        //本次检测完成倒计时
        static void mTimerAllCD_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            TimeSpan ts = mdtStart - DateTime.Now;
            if (ts < TimeSpan.Zero)
            {
                ServiceProvider.Monitor.CompleteCountDown = "00:00";
                mTimerCountDown.Stop();
            }
            else
            {
                ServiceProvider.Monitor.CompleteCountDown = string.Format("{0:D2}:{1:D2}", ts.Minutes, ts.Seconds);
            }
        }
        #endregion 

        #region 开始检测
        /// <summary>
        /// 开始检测
        /// </summary>
        public static void RunDetectChain()
        {

            // DetectChainHelper.Connect();

            ServiceProvider.Monitor.IsRunning = true;
            //AddReagent1AndSample.SA.MainOpen();//总阀

            //IncubationBox.BedControl.Rock();
            ServiceProvider.Monitor.NeedStrips = ServiceProvider.gReactionStripList;

            detectTimer = new System.Timers.Timer();
            detectTimer.AutoReset = false;
            detectTimer.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                runTimer();

                if (ServiceProvider.Monitor.IsRunning)
                    detectTimer.Start();
                else
                    detectTimer.Close();

            });
            detectTimer.Interval = 100.0;
            detectTimer.Enabled = true;
            detectTimer.Start();


            cupLoddTimer = new System.Timers.Timer();
            cupLoddTimer.AutoReset = false;
            cupLoddTimer.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                pushCup();
                if (ServiceProvider.Monitor.IsRunning)
                    cupLoddTimer.Start();
                else
                    cupLoddTimer.Close();
            });
            cupLoddTimer.Interval = 500.0;
            cupLoddTimer.Enabled = true;
            cupLoddTimer.Start();

            mdtStart = DateTime.Now.AddSeconds(90 * ServiceProvider.gReactionStripList.Count).AddMinutes(40);
            mTimerCountDown.Start();

            BackgroundWorker back = new BackgroundWorker();
            back.DoWork += (bss, bee) =>
            {
                while (ServiceProvider.Monitor.IsRunning)
                {
                    ArmMoveControl.MoveArmToRegentOrSample();
                    Thread.Sleep(50);
                }
            };
            back.RunWorkerAsync();

        }

        //大臂操作部分
        private static void runTimer()
        {
            if (ServiceProvider.gReactionCupList.Count > 0)  //如存在需要反应的反应条
            {


                // Console.WriteLine(" 反应杯的链条 有数据 >0  ");//查看反应步骤   2017.8.15 
                int i;
                //便利定义的状态集合
                for (i = 0; i < ServiceProvider.CupStrip.Count; i++)
                {
                    //判断是否有杯子     
                    if (ServiceProvider.CupStrip[i].getStatus() == Model.DetectionModel.CupStrip.ReactionStripStatusEnum.LOAD)
                    {
                        Console.WriteLine(" 杯子的状态已经被加载  ");

                        //进行for循环进行判断杯条中哪个孔位可以下放
                        int j;
                        for (j = 0; j < ServiceProvider.CupStrip[i].Cups.Count; j++)
                        {

                            //判断是否可以放杯子操作
                            if (ServiceProvider.CupStrip[i].Cups[j].getStatus() == Model.DetectionModel.Cup.CupHoleStatusEnum.EMPTY)
                            {

                                Console.WriteLine("分配： 存在有孔位  ");
                                //把孔位号置为HOLEFULL
                                ServiceProvider.CupStrip[i].Cups[j].setStatus(Model.DetectionModel.Cup.CupHoleStatusEnum.FULL);

                                int gg = 0;
                                for (int kk = 0; kk < ServiceProvider.CupStrip[i].Cups.Count; kk++)
                                {

                                    if (ServiceProvider.CupStrip[i].Cups[kk].getStatus() != Model.DetectionModel.Cup.CupHoleStatusEnum.EMPTY)
                                        gg++;
                                    if (gg == 4)
                                        ServiceProvider.CupStrip[i].setStatus(CupStrip.ReactionStripStatusEnum.FULL);
                                }

                                ReactionCup _cup = ServiceProvider.gReactionCupList[0];
                                _cup.CupSeatID = j;
                                _cup.StripID = i;
                                //Application.Current.Dispatcher.Invoke(new Action(() =>
                                //{
                                ServiceProvider.Monitor.DisplayCup[_cup.StripID * 4 + _cup.CupSeatID].DetectItem = _cup.DetectItemModel.detectItem;
                                ServiceProvider.Monitor.DisplayCup[_cup.StripID * 4 + _cup.CupSeatID].SampleInfoID = (int)_cup.SampleInfoID;

                                Console.WriteLine("分配：执行启动链条");

                                BackgroundWorker back = new BackgroundWorker();
                                back.DoWork += (bss, bee) =>
                                {
                                    mDetectChain.Run(_cup);
                                };
                                back.RunWorkerAsync();

                                ServiceProvider.StandardResult[0, 0] = _cup.DetectItem;//给检测结果添加检测名称
                                ////获取 试剂信息
                                //ReagentInfomation reagentInfo = ServiceProvider.getReagentInfomation(_cup, i, j);
                                ////获取样本信息
                                //SampleInfomation sampleInfo = ServiceProvider.getSampleInfomation(_cup, i, j);
                                ServiceProvider.gReactionCupList.Remove(_cup);   //将反应从队列中卸掉

                                //ServiceProvider.Monitor.SampletList.Add(sampleInfo);  //将反应试剂加入执行队列                                


                                //Thread.Sleep(_cup.DetectItemModel.incubationTime1 * 60); //获取数据库中检测的孵育时间                         


                                //ServiceProvider.Monitor.ReagentList.Add(reagentInfo);//将反应的试剂放到试剂集合中                    


                                //}));

                                //跳出for 循环
                                return;
                            }

                        }
                    }
                }
            }
            else    //反应条全部进入
            {
                //反应全部完成
                //此处判断所有反应已做完
                int EmptyCup = 0; //记录UNLOAD条数
                int endCup = 0; //记录反应完成CUP数
                for (int k = 0; k < 4; k++)
                {
                    for (int m = 0; m < 4; m++)
                    {
                        if (ServiceProvider.CupStrip[k].Cups[m].getStatus() == Model.DetectionModel.Cup.CupHoleStatusEnum.END)
                        {
                            endCup++;
                        }
                        else if (ServiceProvider.CupStrip[k].Cups[m].getStatus() == Model.DetectionModel.Cup.CupHoleStatusEnum.EMPTY)
                        {
                            EmptyCup++;
                        }
                    }
                }

                if (((endCup + EmptyCup) == 16) && (endCup > 0))
                {

                    //ServiceProvider.Monitor.DetectEndStatusEnum.setStatus(DetectEndStatusEnum.DetectEndEnum.DETECTEND);
                    //MessageBox.Show("反应全部完成，请置初始状态！");

                    DetectChainHelper.DetectionOrder.CupList.Clear();
                    ServiceProvider.Monitor.IsRunning = false;
                    //主窗口中 暂停按钮变成 启动状态。。。。如何变？ 主窗体中添加时钟监控 isRunning状态吗？

                    if (ServiceProvider.ISCheckSave)
                    {
                        for (int ii = 0; ii < ServiceProvider.shortCalibraList.Count; ii += 2)
                        {
                            double calResult = (ServiceProvider.shortCalibraList[ii] + ServiceProvider.shortCalibraList[ii + 1]) / 2;
                            ServiceProvider.calibrationList.Add(calResult);
                        }

                        //定标浓度
                        double sampleCon = ServiceProvider.SampleConcentration * 2;
                        //给结果集合添加结果
                        for (int i = 0; i < ServiceProvider.calibrationList.Count; i++)
                        {
                            ServiceProvider.StandardResult[i + 1, 0] = sampleCon.ToString("#.##");
                            ServiceProvider.StandardResult[i + 1, 1] = ServiceProvider.calibrationList[i].ToString();
                            sampleCon /= 2 * (i + 1);
                        }

                        //判断是否存在当前检测项  如果存在则去更新操作
                        if (standardBll.CheckExist(ServiceProvider.SelectedValues))
                        {
                            standardBll.updateStandardCurveData(getStandardModel(ServiceProvider.StandardResult));
                        }
                        else  //不存在则开始插入一条数据
                        {
                            standardBll.insertStandardCurveModel(getStandardModel(ServiceProvider.StandardResult));
                        }
                        //ServiceProvider.shortCalibraList.Clear();
                        //ServiceProvider.calibrationList.Clear();
                        ServiceProvider.ISCheckSave = false;
                    }
                }
            }
        }

        //细化方法
        public static StandardCurveData getStandardModel(string[,] standardResult)
        {
            List<double> concentrationLogList = new List<double>();//对数集合
            List<double> detectResultLogList = new List<double>();//对数集合

            List<double> concentrationList = new List<double>();  //普通集合
            List<double> detectResultList = new List<double>();   //普通集合

            //存在则开始更新检测项
            StandardCurveData model = new StandardCurveData();
            try
            {
                //记录检测浓度
                model.DetectItem = ServiceProvider.StandardResult[0, 0];
                model.Concentration1 = Convert.ToDouble(standardResult[1, 0]);
                model.Concentration2 = Convert.ToDouble(standardResult[2, 0]);
                model.Concentration3 = Convert.ToDouble(standardResult[3, 0]);
                model.Concentration4 = Convert.ToDouble(standardResult[4, 0]);
                // model.Concentration5 = Convert.ToDouble(standardResult[5, 0]);

                concentrationLogList.Add(Math.Log10(model.Concentration1));
                concentrationList.Add(model.Concentration1);
                concentrationLogList.Add(Math.Log10(model.Concentration2));
                concentrationList.Add(model.Concentration2);
                concentrationLogList.Add(Math.Log10(model.Concentration3));
                concentrationList.Add(model.Concentration3);
                concentrationLogList.Add(Math.Log10(model.Concentration4));
                concentrationList.Add(model.Concentration4);
                //concentrationLogList.Add(Math.Log10(model.Concentration5));
                //concentrationList.Add(model.Concentration5);


                //if (standardResult[6, 0] == null)
                //{
                //    model.Concentration6 = 0;
                //}
                //else
                //{
                //    model.Concentration6 = Convert.ToDouble(standardResult[6, 0]);
                //    concentrationLogList.Add(Math.Log10(model.Concentration6));
                //    concentrationList.Add(model.Concentration6);
                //}

                //记录检测结果   检测结果
                if (standardResult[1, 1].Equals(""))
                {
                    model.DetectResult1 = 0.00;
                }
                else
                {
                    model.DetectResult1 = Convert.ToDouble(standardResult[1, 1]);
                    detectResultLogList.Add(Math.Log10(Convert.ToDouble(model.DetectResult1)));
                    detectResultList.Add(model.DetectResult1);
                }

                if (standardResult[2, 1].Equals(""))
                {
                    model.DetectResult2 = 0;
                }
                else
                {
                    model.DetectResult2 = Convert.ToDouble(standardResult[2, 1]);
                    detectResultLogList.Add(Math.Log10(Convert.ToDouble(model.DetectResult2)));
                    detectResultList.Add(model.DetectResult2);
                }

                if (standardResult[3, 1].Equals(""))
                {
                    model.DetectResult3 = 0;
                }
                else
                {
                    model.DetectResult3 = Convert.ToDouble(standardResult[3, 1]);
                    detectResultLogList.Add(Math.Log10(Convert.ToDouble(model.DetectResult3)));
                    detectResultList.Add(model.DetectResult3);
                }
                if (standardResult[4, 1].Equals(""))
                {
                    model.DetectResult4 = 0;
                }
                else
                {
                    model.DetectResult4 = Convert.ToDouble(standardResult[4, 1]);
                    detectResultLogList.Add(Math.Log10(Convert.ToDouble(model.DetectResult4)));
                    detectResultList.Add(model.DetectResult4);
                }

                //if (standardResult[5, 1].Equals("") || standardResult[5, 1] == null)
                //{
                //    model.DetectResult5 = 0;
                //}
                //else
                //{
                //    model.DetectResult5 = Convert.ToDouble(standardResult[5, 1]);
                //    detectResultLogList.Add(Math.Log10(Convert.ToDouble(model.DetectResult5)));
                //    detectResultList.Add(model.DetectResult5);
                //}

                //if (standardResult[6, 1] == null)
                //{
                //    model.DetectResult6 = 0;
                //}
                //else
                //{
                //    model.DetectResult6 = Convert.ToDouble(standardResult[6, 1]);
                //    detectResultLogList.Add(Math.Log10(Convert.ToDouble(model.DetectResult6)));
                //    detectResultList.Add(model.DetectResult6);
                //}

                List<double> logCoefficientB = ServiceProvider.Algorithmclass.setCoefficientB(concentrationLogList, detectResultLogList);
                List<double> ordinaryCeofficientB = ServiceProvider.Algorithmclass.setCoefficientB(concentrationList, detectResultList);


                // model.OrdinaryCoefficientB = 0;
                model.FileTime = DateTime.Now;
                model.LineValue = ServiceProvider.Algorithmclass.getLineValue(concentrationLogList, detectResultLogList);  //计算对数相关系数值
                model.OrdinaryLineValue = ServiceProvider.Algorithmclass.getLineValue(concentrationList, detectResultList); //计算普通相关系数值
                model.CoefficientB = logCoefficientB[2];                                 //计算对数回归线性方程系数（b） 
                model.ConstantA = Math.Round(logCoefficientB[1] - logCoefficientB[2] * logCoefficientB[0], 3);//计算对数回归线性方程常数（a）
                model.OrdinaryCoefficientB = ordinaryCeofficientB[2];                          //计算普通回归方程系数（b）
                model.OrdinaryConstantA = Math.Round(ordinaryCeofficientB[1] - ordinaryCeofficientB[2] * ordinaryCeofficientB[1], 3);//计算普通回归方程常数（a）


            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return model;
        }

        //推杯子
        public static void pushCup()
        {
            if (ServiceProvider.gReactionCupList.Count > 0)
            {

                for (int i = 0; i < ServiceProvider.CupStrip.Count; i++)
                {
                    if (ServiceProvider.CupStrip[i].getStatus() == CupStrip.ReactionStripStatusEnum.LOAD)
                    {//改变执行状态

                        Console.WriteLine("不用推杯子：有空杯子！！！");

                        break;
                    }
                    else
                    {
                        if (ServiceProvider.CupStrip[i].getStatus() == CupStrip.ReactionStripStatusEnum.UNLOAD)
                        {

                            Console.WriteLine("推杯子：没有空杯子  - " + i.ToString() + " 有未装载的条  --开始00执行推杯子任务00");
                            //ServiceProvider.CupStrip[i].setStatus(CupStrip.ReactionStripStatusEnum.LOAD);

                            DeliveryCupControl.PushMeTo(i);

                            ServiceProvider.CupStrip[i].init();

                            for (int j = 0; j < 4; j++)// 王冬冬 2017.8.22 晚  21：57！！！
                            {
                                ServiceProvider.Monitor.DisplayCup[i * 4 + j].DetectItem = "";
                                ServiceProvider.Monitor.DisplayCup[i * 4 + j].SampleInfoID = 0;
                                ServiceProvider.Monitor.DisplayCup[i * 4 + j].CupStatus = "空";
                            }
                            break;
                        }
                    }
                }
            }
        }

        public void ArmMoveToSampleAndReagent()
        {

            if (ServiceProvider.Monitor.SampletList.Count != 0 || ServiceProvider.Monitor.ReagentList.Count != 0)
            {
                ReagentInfomation reagentInfomation = ServiceProvider.Monitor.ReagentList[0];
                if (reagentInfomation != null)//进行解析执行试剂链条中的吸试剂的方法
                {
                    ServiceProvider.Monitor.ReagentList.Remove(reagentInfomation);
                    //执行方法去移动
                }

                SampleInfomation sampleInfomation = ServiceProvider.Monitor.SampletList[0];
                if (sampleInfomation != null)//进行解析执行样本链条中的吸试剂的方法
                {
                    ServiceProvider.Monitor.SampletList.Remove(sampleInfomation);
                }
            }
        }


        #endregion
        /// <summary>
        /// 暂停检测
        /// </summary>
        public static void PauseDetect()
        {

        }

        /// <summary>
        /// 记录位置
        /// </summary>
        /// <param name="position"></param>
        public static void Position(int position)
        {
            mPositionDal.Add(new Model.ReactionStripPosition() { Position = position });
        }
        /// <summary>
        /// 删除位置
        /// </summary>
        /// <param name="position"></param>
        public static void UnPosition(int position)
        {
            mPositionDal.Delete(position);
        }
        #endregion 运行控制

        #region 发送数据事件

        /// <summary>
        /// 连接仪器
        /// </summary>
        public static void Connect()
        {
            if (Can.ConnectCan())
            {
                ServiceProvider.Monitor.USBConnectState = ComponentStateEnum.NORMAL;
            }
            else
            {
                ServiceProvider.Monitor.USBConnectState = ComponentStateEnum.ERROR;
            }
        }

        //发送命令后执行事件
        static void Can_Decode_Send(Int16 canID, string command)
        {
            //ControlBase.mSendBuffer.Add(new CmdModel(canID, command));

        }
        /// <summary>
        /// 重发超时命令
        /// </summary>
        public static void ReSend()
        {
            for (int i = 0; i < ControlBase.mSendBuffer.Count; i++)
            {
                CmdModel cmdModel = ControlBase.mSendBuffer[i];
                string command = cmdModel.Cmd;
                short canID = cmdModel.CanId;
                string _key = "";
                if (command.Length < 5)
                {
                    _key = canID + command.Substring(0, 2);
                }
                else
                {
                    _key = canID + command.Substring(0, 3);
                }
                Can.SendCan(cmdModel.CanId, cmdModel.Cmd);
            }
            ControlBase.mSendBuffer.Clear();
        }
        /// <summary>
        /// 开始监测孵育箱温度
        /// </summary>
        public static void GetTemperature()
        {
            //开试剂冷却温控                     
            IncubationBox.IncubationControl.Begin();

            //开启试剂针温控
            IncubationBox.IncubationControl.BeginReagentT();
            //设置试剂针温度
            IncubationBox.IncubationControl.SetReagentNeedleTemperature(ServiceProvider.Monitor.MdcConfiger.reagentNeedleTem);//温度的问题

            IncubationBox.IncubationControl.SetReagentCupsTemperature(ServiceProvider.Monitor.MdcConfiger.detectAreaTem); //37检测位温度


            //Can.SendCan(65, "1IF2100" + "\r");   //设置试剂针的灵敏度   NO.1标准
            //Can.SendCan(65, "1IF1050" + "\r");

            Can.SendCan(65, "1IF2999" + "\r");   //设置试剂针的灵敏度  999   NO.2标准
            Can.SendCan(65, "1IF1999" + "\r");


            mTemperatureTimer = new System.Timers.Timer();
            mTemperatureTimer.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                IncubationBox.IncubationControl.GetTemperature();
                IncubationBox.IncubationControl.GetKitTemperature();
                // IncubationBox.IncubationControl.SetReagentCupsTemperature(36);

                //   IncubationBox.IncubationControl.SetReagentNeedleTemperature(3700);
                //   IncubationBox.IncubationControl.GetReagentNeedleTemperature();
                Thread.Sleep(100);

                IncubationBox.Temperature.Add(Can.ReagentTemp[0]);
                IncubationBox.Temperature.Add(Can.ReagentTemp[1]);

                IncubationBox.Temperature.Add(Can.ReagentTemp[3]);
                //计算 温度
                for (int i = 0; i < 4; i++)
                {
                    detectTemp += Can.CupTemp[i];
                }
                detectTemp = detectTemp / 4;

                ServiceProvider.Monitor.DetectTemp = (float.Parse(detectTemp.ToString()) / 100).ToString();
                detectTemp = 0;
                ServiceProvider.Monitor.ReagentTemp = Can.ReagentTemp[0];

            });
            mTemperatureTimer.Interval = 5000;
            mTemperatureTimer.Start();

            ArmMoveControl.DoorStatus = 0; //重置状态
            mDoorTimer = new System.Timers.Timer();   //判断门是否处于打开状态的计时器
            mDoorTimer.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                Can.SendCan(88, "1DS3" + "\r");

                if (ArmMoveControl.DoorStatus == 1)   //门是开着的  1表示
                {
                    ArmMoveControl.DoorStatus = 0; //重置状态
                    ArmMoveControl.IsPause = true;
                    DeliveryCupControl.IsPause = true;
                }
                else if (ArmMoveControl.DoorStatus == 2) // 门是关着的  2表示
                {
                    ArmMoveControl.DoorStatus = 0; //重置状态
                    ArmMoveControl.IsPause = false;
                    DeliveryCupControl.IsPause = false;
                }

            });
            mDoorTimer.Interval = 1000;
            mDoorTimer.Start();

            ServiceProvider.Monitor.DetectTemp = "0"; //覆初始值
            IncuBoxStateTime = new System.Timers.Timer();
            IncuBoxStateTime.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                if (through)
                {
                    through = false;
                    ServiceProvider.Monitor.IncubationBoxState = ComponentStateEnum.NORMAL;  //红色图标
                }
                else
                {
                    through = true;
                    ServiceProvider.Monitor.IncubationBoxState = ComponentStateEnum.ALERT;   //灰色图标                 
                }

                if (Convert.ToDouble(ServiceProvider.Monitor.DetectTemp) > 36.5) //如果大于36.5度进行关闭闪烁
                {
                    IncuBoxStateTime.Close();
                    through = false;  //关闭闪烁
                    ServiceProvider.Monitor.IncubationBoxState = ComponentStateEnum.ERROR;  //绿色图标
                }
            });
            IncuBoxStateTime.Interval = 1000;
            IncuBoxStateTime.Start();

            ReagentColdStateTime = new System.Timers.Timer();
            ReagentColdStateTime.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
            {
                if (reagentColdThrough)
                {
                    reagentColdThrough = false;
                    ServiceProvider.Monitor.ReagentPlate1State = ComponentStateEnum.NORMAL;  //红色图标
                }
                else
                {
                    reagentColdThrough = true;
                    ServiceProvider.Monitor.ReagentPlate1State = ComponentStateEnum.ALERT;   //灰色图标                 
                }

                if ((ServiceProvider.Monitor.ReagentTemp < 1700) && (ServiceProvider.Monitor.ReagentTemp != 0)) //如果大于16度进行关闭闪烁
                {
                    ReagentColdStateTime.Close();
                    reagentColdThrough = false;  //关闭闪烁
                    ServiceProvider.Monitor.ReagentPlate1State = ComponentStateEnum.ERROR;  //绿色图标
                }
            });
            ReagentColdStateTime.Interval = 1000;
            ReagentColdStateTime.Start();


        }

        /// <summary>
        /// 开始摇晃
        /// </summary>
        //public static void Rock()
        //{
        //    mRockTimer = new System.Timers.Timer();
        //    mRockTimer.Elapsed += new System.Timers.ElapsedEventHandler((ss, ee) =>
        //    {
        //        if (Transportation.IncubationTransport.Status != -10 && Transportation.IncubationTransport.Status != -11)//正在取放反应条
        //            IncubationBox.BedControl.WaitStatus(IncubationBox.BedControl.Rock());
        //    });
        //    mRockTimer.Interval = 10000;
        //    mRockTimer.Start();
        //}
        /// <summary>
        /// 停止摇晃
        /// </summary>
        public static void StroRock()
        {
            //mRockTimer.Enabled = false;
            Can.SendCan(97, "1ST" + Can.strEnd);
            IncubationBox.BedControl.WaitStatus(IncubationBox.BedControl.Reset());

        }

        #endregion

        #region 接受数据
        /// <summary>
        /// 接收数据
        /// </summary>
        public static void RunRecieveData()
        {
            BackgroundWorker back = new BackgroundWorker();
            back.DoWork += (bss, bee) =>
            {
                while (true)
                {
                    Can.RecieveData();
                    //ReSend();
                    Thread.Sleep(10);
                    //Can.SendCan(88, "2AC200" + "\r");

                }
            };
            back.RunWorkerAsync();
        }

        /// <summary>
        /// 接收数据方法事件
        /// </summary>
        static void Can_Decode_Receive(int canID, string recieve)
        {
            try
            {
                Console.WriteLine(recieve);

                //return;
                //recieve = recieve.Replace("?\r", "");
                //string[] data = recieve.Split(';');
                string strReturn = "";
                //foreach (string strReturn in data)
                //{
                //if (recieve != "")
                //    {
                switch (canID)
                {
                    case 0x93: //X轴接受状态 处理
                        {
                            break;
                        }
                    case 0x92: //X轴接受状态 处理
                        {
                            break;
                        }
                    case 0x81: //Z轴接受状态 处理
                        {
                            break;
                        }
                    //case DeliveryCupControl.RBeltMotorID: //皮带接受状态
                    //            {
                    //                DeliveryCupControl.BeltMotorStatus = 1;
                    //                break;
                    //            }
                    //case DeliveryCupControl.RHookMotorID: //钩子状态
                    //            {
                    //                DeliveryCupControl.HookMotorStatus = 1;
                    //                break;
                    //            }
                    //case DeliveryCupControl.RCarMotorID: //小车状态
                    //            {
                    //                DeliveryCupControl.CarMotorStatus = 1;
                    //                break;
                    //            }
                    //case DeliveryCupControl.RPoleMotorID: //推杆状态
                    //            {
                    //                DeliveryCupControl.PoleMotorStatus = 1;
                    //                break;
                    //            }
                    #region 查询孵育箱温度、试剂箱温度、获取光强值、条码值
                    default:
                        //查询孵育仓的温度
                        if (strReturn.Contains("CX"))
                        {
                            IncubationBox.Temperature.Clear();
                            string[] temps = strReturn.Split(',');

                            for (int i = 1; i < temps.Length; i++)
                            {
                                if (temps[i].Length > 2)
                                {
                                    string temp = temps[i].Insert(temps[i].Length - 2, ".");
                                    IncubationBox.Temperature.Add(double.Parse(temp));
                                }

                            }
                            ServiceProvider.Monitor.IncubatorTempurature = IncubationBox.TemperatureAVG;
                        }
                        else if (strReturn.Contains("CS"))//试剂区
                        {
                            AddReagent1AndSample.Temperature.Clear();
                            string[] temps = strReturn.Split(',');
                            for (int i = 1; i < temps.Length; i++)
                            {
                                if (temps[i].Length > 2)
                                {
                                    string temp = temps[i].Insert(temps[i].Length - 2, ".");
                                    AddReagent1AndSample.Temperature.Add(double.Parse(temp));
                                }
                            }

                            ServiceProvider.Monitor.KitTempurature = AddReagent1AndSample.TemperatureAVG;
                        }
                        else if (strReturn.Contains("V"))//光强值
                        {
                            DetectionHouse.CurrentLightValue = int.Parse(strReturn.Substring(1));
                            DetectionHouse.DetectControl.Status = 7;
                        }
                        else if (strReturn.Contains("BA"))
                        {
                            string _barcode = strReturn.Substring(2, strReturn.Length - 4);
                            AddReagent1AndSample.CurrentBarcode = _barcode;
                        }
                        else
                        {
                            Console.WriteLine("-----------------------" + strReturn + "----------------");
                        }
                        break;
                        #endregion
                }//end switch
                 //}//end if
                 //}//end foreach
            }
            catch (Exception ex)
            {
                Console.WriteLine("------------ex-----------" + ex.Message);
            }
        }

        /// <summary>
        /// 处理运行信息
        /// </summary>
        public static void PostMessage(int messageCode)
        {
            ServiceProvider.WaitMessage.Add(messageCode);
        }

        #endregion 接受数据
    }
}
